<template>
  <div class="upload-files" v-loading="loading">
    <el-upload class="upload-demo"
      :action="fileApiUri"
      :limit="limit"
      :headers="token"
      :on-exceed="handleExceed"
      :before-upload="validateFile"
      :on-success ="updataSuccess"
      :before-remove="delFile"
      :file-list="fileList">
      <el-button size="small" type="primary">Upload</el-button>
    </el-upload>
  </div>
</template>

<script>
  import {
    deleteFile
  } from '@/api/files'
  import {
    getAccessToken
  } from '@/utils/auth'
  export default {
    name: 'UploadFile',
    props: ["fileList","limit"],
    data() {
      return {
        maxLimit: 3,
        token: {
          "Authorization": getAccessToken()
        },
        fileApiUri: process.env.BASE_API + '/api/file/upload',
        loading: false,
      }
    },
    methods: {
      validateFile(file) {
        this.loading = true;
        const rightType = function(type) {
          let fileType = [
            "image/jpeg",
            "image/png",
            "image/gif",
            "application/msword",
            "application/zip",
            "application/rar",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            "application/pdf",
            "application/haansofthwp",
            "text/plain",
          ]
          for (let i = 0; i < fileType.length; i++) {
            if (fileType[i] === type) return false
          };
          return true
        }
        const isJPG = rightType(file.type) ? false : true;
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isJPG) {
          this.$message.error('.jpg/.png/.gif/.zip/.rar/.doc/.pptx/.xlsx/.pdf/.txt/.hwp 파일 업로드 가능합니다');
          this.loading = false;
        }
        if (!isLt5M) {
          this.$message.error('최대 5MB 첨부가능합니다!');
          this.loading = false;
        }
        return isJPG && isLt5M
      },
      handleExceed(files, fileList) {
        this.$message.warning(`최대 3개의 파일 첨부가능합니다`);
      },
      updataSuccess(response, file, fileList) {
        this.loading = false;
        if(response.code===200){
          this.$emit('addFile', response.data);
          this.$message({
            type: 'success',
            message: '업로드 되엿습니다'
          });
        }else{

        }
      },
      delFile(file, fileList) {
        if (file.raw !== undefined) return true //跳过临时文件
        return new Promise((resolve, reject) => {
          this.$confirm('회복할 수 없는 조작입니다!', '팁스', {
            confirmButtonText: '삭제',
            cancelButtonText: '취소',
            type: 'warning'
          }).then(() => {
            this.loading = true;
            deleteFile(file).then(valid => {
              if (valid) {
                this.$emit('deleteFile', file.id);
                this.$message({
                	type: 'success',
                	message: '삭제되엿습니다'
                });
                this.loading = false;
                return false;
              } else {
                this.loading = false
                console.log('error submit!!')
                return false
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '취소되엿습니다'
            });
            reject()
          });
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload-files {
  width: 500px;
}
</style>
